var amzDappAddress = 'n1zAKhRRAfwr7zqafBhvpMcKHoWpyKAcQ4d';
var dappAddress = 'n1o6BdGCRARnGiLdogi32Qz38YBszGRbQt4';
var hash = "ffffdad4a85cc3965c21e76190bf2132a5dbc49301814c7aa96308cf9e449283";
var NebPay = require("nebpay");
var nebPay = new NebPay();
var amzInfo = null;
var isOpenAssets = false;
var isOpenVote = false;
var targetToken = null; // 选择到的币 切换图用的

if (typeof nebPay.simulateCall == "undefined" || typeof nebPay.call == "undefined") {
  alert('检测到您未开启星云钱包插件,请启动并刷新页面。 如果您确认有开启,请刷新浏览器！');
}

function toast (text) {
  $('#toast').html(text);
  $('#toast').show();
  setTimeout(function () {
    $('#toast').addClass('toast-show');
    showToast()
  }, 300);
}

function showToast () {
  setTimeout(function () {
    $('#toast').removeClass('toast-show');
    setTimeout(function () {
      $('#toast').hide();
    }, 2300);
  }, 5000);
}

function getWallectInfo () {
  window.postMessage({
    "target": "contentscript",
    "data": {},
    "method": "getAccount"
  }, "*");
  window.addEventListener("message", function (e) {
    if (e.data && e.data.data && e.data.data.account) {
      window.address = e.data.data.account;
      $('#address').html(e.data.data.account);
    }
  })
}
getWallectInfo();

var timer;

function signIn () {
  nebPay.simulateCall(amzDappAddress, "0", "getUserInfo", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      
      var info = JSON.parse(res.result);
      if (!info) {
        toast('您尚未注册,系统正在自动注册中...');
        register()
      } else {
        amzInfo = JSON.parse(info);
        renderHtml(JSON.parse(info));
        tokenArr();
      }
    }
  })
}

signIn();

function register () {
  nebPay.call(amzDappAddress, "0", "register", JSON.stringify([]), { 
    listener: function(res) {
      toast(res.txhash ? '大约需要30秒左右,请稍后...' : '注册失败.请刷新页面重试！！！');
      getUserInfo()
    }
  })
}

function getUserInfo () {
  timer = setInterval(function () {
    nebPay.simulateCall(amzDappAddress, "0", "getUserInfo", JSON.stringify([]), {
      listener: function(res) {
        if(res.result == '' && res.execute_err == 'contract check failed') {
            toast('合约检测失败，请检查浏览器钱包插件环境！');
            return;
        }
        var info = JSON.parse(res.result);
        if (info) {
          amzInfo = JSON.parse(info);
          renderHtml(JSON.parse(info));
          clearInterval(timer);
          tokenArr();
        }
      }
    })
  }, 5000)
}
// 渲染我的资产
function renderHtml (amzInfo) {
  var html = '';
  var add = '';
  if (amzInfo.token.length) {
    for (var i = 0; i < amzInfo.token.length; i++) {
      html += '<div><span>'+amzInfo.token[i].tokenName+'</span><span>'+amzInfo.token[i].tokenNum+'</span></div>'
    }
  } else {
    html += '<p>暂无资产,你可以尝试去https://p8p7.gitee.io/wallet领取空投,或者购买资产</p>'
  }
  
  $('#menu-footer').html(html);
}
//渲染我的上币
function renderVote (tokenArr) {
  // 这里是产品列表
  $('#product-varieties').html(tokenArr[0] + '/NAS');
  targetToken = tokenArr[0];
  $('#trade-price-title').html('1NAS等于多少'+targetToken);
  $('#trade-price-num').html('买入多少NAS的'+targetToken);


  var tokenHtml = '';
  for (var i = 0; i < tokenArr.length; i++) {
    tokenHtml += '<span>'+ tokenArr[i] +'</span>'
  }
  $('#varieties').html(tokenHtml);

  // 我要上币的币的列表
  var voteArr = amzInfo.token.filter(function (key) {
    return !tokenArr.includes(key.tokenName)
  })
  var html = '';
  for (var i = 0; i < voteArr.length; i++) {
    html += '<span>'+ voteArr[i].tokenName +'</span>'
  }
  $('#vote-footer').html(html);
}
 // 获取交易所目前有的币种
function tokenArr () {
  nebPay.simulateCall(dappAddress, "0", "getTokenAll", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      var info = JSON.parse(res.result);
      renderVote(info ? JSON.parse(info) : []);
    }
  })
}

// 切换买入
$('#purchase-menu').on('click', function () {
  $('#direction').removeClass('active-sell-out').addClass('active-purchase');
  $('#trade-btn').html('委托买入').css('background', '#e65252');
  $('#trade-price-num').html('买入多少NAS的'+targetToken);
})

// 切换卖出
$('#sell-out-menu').on('click', function () {
  $('#direction').removeClass('active-purchase').addClass('active-sell-out');
  $('#trade-btn').html('委托卖出').css('background', '#48b147');
  $('#trade-price-num').html('卖出多少NAS的'+targetToken);
})

// 打开资产
$('#assets').on('click', function () {
  if (isOpenVote) {
    $('#vote-body').removeClass('open-menu-body');
    isOpenVote = false;
    setTimeout(function () {
      if (!isOpenAssets) {
        $('#menu-body').addClass('open-menu-body');
        isOpenAssets = true;
      } else {
        $('#menu-body').removeClass('open-menu-body');
        isOpenAssets = false;
      }
    }, 600);
  } else {
    if (!isOpenAssets) {
      $('#menu-body').addClass('open-menu-body');
      isOpenAssets = true;
    } else {
      $('#menu-body').removeClass('open-menu-body');
      isOpenAssets = false;
    }
  }
})

// 关闭资产
$('#close-menu').on('click', function () {
  isOpenAssets = false;
  $('#menu-body').removeClass('open-menu-body');
})

// 打开上币
$('#vote').on('click', function () {
  if (isOpenAssets) {
    $('#menu-body').removeClass('open-menu-body');
    isOpenAssets = false;
    setTimeout(function () {
      if (!isOpenVote) {
        isOpenVote = true;
        $('#vote-body').addClass('open-menu-body');
      } else {
        isOpenVote = false;
        $('#vote-body').removeClass('open-menu-body');
      }
    }, 600);
  } else {
    if (!isOpenVote) {
      isOpenVote = true;
      $('#vote-body').addClass('open-menu-body');
    } else {
      isOpenVote = false;
      $('#vote-body').removeClass('open-menu-body');
    }
  }
})

// 关闭上币
$('#close-vote').on('click', function () {
  isOpenVote = false;
  $('#vote-body').removeClass('open-menu-body');
})

var isOpenProduct = false;
// 打开产品列表
$('#product').on('click', function () {
  if (!isOpenProduct) {
    isOpenProduct = true;
    $('#varieties').addClass('open-varieties');
  } else {
    isOpenProduct = false;
    $('#varieties').removeClass('open-varieties');
  }
})

// 选择token 渲染chat等等。
$('#varieties').on('click', 'span', function () {
  targetToken = $(this).html();
  isOpenProduct = false;
  $('#trade-price-title').html('1NAS等于多少'+targetToken);
  $('#product-varieties').html(targetToken+'/NAS');
  if ($('#direction').hasClass('active-purchase')) {
    $('#trade-price-num').html('买入多少NAS的'+targetToken);
  } else {
    $('#trade-price-num').html('卖出多少NAS的'+targetToken);
  }
  $('#varieties').removeClass('open-varieties');
  $('#iframe').attr('src', './chat.html?tokenName=' + targetToken);
})

// 上币 选择的币
var voteToken = null;
$('#vote-footer').on('click', 'span', function () {
  voteToken = $(this).html();
  $(this).addClass('active').siblings().removeClass('active');
})

$('#vote-btn').on('click', function () {
  if (voteToken) {
    nebPay.call(dappAddress, "0", "addToken", JSON.stringify([voteToken]), { 
      listener: function(res) {
        initTime = Date.now();
        toast(res.txhash ? '上币成功请一分钟后刷新页面' : '上币失败！！！');
      }
    })
  }
})






$('#trade-btn').on('click', function () {
  var type = null; // 1是买 2是卖
  if ($('#direction').hasClass('active-purchase')) {
    type = 1
  } else {
    type = 2
  }
  var num = $('#num').val();
  var rate = $('#rate').val();
  if (!num || !rate || !targetToken) {
    toast('请填写完整信息');
    return false
  }
  trade(type, num, rate);
})

function trade (type, num, rate) {
  if (type == 1) {
    nebPay.call(dappAddress, num, "buy", JSON.stringify([rate, num, targetToken]), { 
      listener: function(res) {
        toast(res.txhash ? '委托成功' : '委托失败！！！');
      }
    })
  } else {
    var hash = 'amz_hash' + Date.now() + ~~(Math.random() * 1e6);
    

    nebPay.call(amzDappAddress, "0", "transaction", JSON.stringify([targetToken, "n1X7NJbKyVz5wAsvaupBYt52fS76d38sStc", +rate * +num, hash]), { 
      listener: function(res) {
        if (res.txhash) {
          toast('扣币成功,1分钟后系统会自动发起委托交易,请耐心等待');
          entrust(rate, num)
        }
      }
    })

  }
}

function entrust (rate, num) {
  setTimeout(function () {
    nebPay.call(dappAddress, "0", "sell", JSON.stringify([rate, num, targetToken]), { 
      listener: function(res) {
        toast(res.txhash ? '委托成功' : '委托失败！！！');
      }
    })
  }, 1000 * 60);
}

$('#matchmaking').on('click', function () {
  nebPay.call(dappAddress, "0", "trade", JSON.stringify([]), { 
    listener: function(res) {
      toast(res.txhash ? '感谢你' : '撮合失败！！！');
    }
  })
})

function getAssets () {
  nebPay.simulateCall(dappAddress, "0", "getAssets", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      var info = JSON.parse(res.result);
      renderExchangeAssets(info)
    }
  })
}
getAssets();
function renderExchangeAssets (data) {
  var html = '';
  if (data) {
    data = JSON.parse(data);
    for (var i = 0; i < data.length; i++) {
      html += '<div class="exchange-assets-item"><span>'+data[i].tokenName+'</span><span>'+data[i].tokenNum+'</span><a class="exchange-item">提币</a></div>'
    }
  } else {
    html += '<p>暂无交易所资产,快去购买吧</p>'
  }
  $('#exchange-assets').html(html)
}

$('body').on('click', '.exchange-item', function () {
  var tokenName = $(this).parent().find('span').eq(0).html();
  nebPay.call(dappAddress, "0", "withdraw", JSON.stringify([tokenName]), { 
    listener: function(res) {
      toast(res.txhash ? '提币申请成功,5个工作日内会打入你amz协议钱包' : '提币失败！！！');
    }
  })
})

function buyEntrust () {
  nebPay.simulateCall(dappAddress, "0", "getBuy", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      var info = JSON.parse(res.result);
      sellEntrust(info);
    }
  })
}

buyEntrust();

function sellEntrust (buy) {
  nebPay.simulateCall(dappAddress, "0", "getSell", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      var info = JSON.parse(res.result);
      renderEntrustList(buy, info)
    }
  })
}

function renderEntrustList (buy, sell) {
  var buyArr = [];
  var sellArr = [];
  var arr;
  if (buy) {
    buyArr = JSON.parse(buy);
  }

  if (sell) {
    sellArr = JSON.parse(sell);
  }

  arr = buyArr.concat(sellArr);

  arr = arr.filter(function (item) {
    return item.address == window.address
  })

  var html = '';
  for (var i = 0; i < arr.length; i++) {
    html += '<div><p>委托价格1NAS等于'+arr[i].rate + arr[i].tokenName +'</p>'
      + '<p>'+(arr[i].type == '1' ? '买入' : '卖出')+ arr[i].num +'NAS <span data-type="'+arr[i].type+'" data-address="'+arr[i].address+'" data-tokenname="'+arr[i].tokenName+'" data-num="'+arr[i].num+'" data-rate="'+arr[i].rate+'" class="revoke">撤销</span></p></div>'
  }

  $('.history').html(html);
}


$('body').on('click', '.revoke', function () {
  var rate = $(this).data('rate');
  var num = $(this).data('num');
  var tokenName = $(this).data('tokenname');
  var type = $(this).data('type');
  nebPay.call(dappAddress, "0", "revoke", JSON.stringify([rate, num, tokenName, type]), { 
    listener: function(res) {
      toast(res.txhash ? '撤销成功,请一分钟后刷新页面,请同一个委托不要重复撤销' : '撤销失败！！！');
    }
  })
})

$('#go').on('click', function () {
  $('#loading').hide();
})

$('#service').on('click', function () {
  alert('客服邮箱: anmingzhe@me.com');
})
